/**
 * 关键期限
 * @author muisuidaan
 */
import React, { useEffect, useState } from "react";

import { Table, Popover, Select, message, Spin,Dropdown,Menu } from "antd";
import { PageWrapper } from "@/components/PageWrapper";
import CusDatePicker from "@/components/Picker/datePicker";
import { Title } from "@/components/Title";
import { RedBtn } from "@/components/Button";
import Area, { DataProps } from "@/components/EchartsComponents/Area";
import EventEmpty from "@/components/FOF/EventEmpty";
import {
  FormContainer,
  BottomContainer,
  LeftContainer,
  RightContainer,
  RedContainer,
  DateContainer,
  ListContainer,
  List,
  Divider,
  ColorContainer,
  TextContainer,
  ButtonContainer,
  DeleteBtnContainer,
  DeleteBtn,
} from "./components/container";
import CustomizeRadio from "@/components/CustomizeRadio";
import GraphOrTable from "@/components/CustomizeRadio/graphOrTable";

import { ColumnsType } from "antd/lib/table";
import { getMergeFromChildList, toFixed } from "@/utils/utils";
import { getBaseColors } from "@/utils/echarts";
import { AxisArr } from "@/utils/echarts";

import select_arrow from "@/assets/icons/icon-arrow.png";


import * as _ from "lodash";
import cn from "classnames";
import dayjs from 'dayjs';

// import axios from "axios";

// const controller = new AbortController();

// const CancelToken = axios.CancelToken;
// const source = CancelToken.source();

import {
  get_critical_deadline_table,
  get_critical_deadline_chart,
  get_first,
  teaching_log,
  get_critical_deadline_percent
} from "./criticalPeriod";
import { get_last_trading_date } from "@/service/global";

import styles from "./index.less";
// import common_pop from "@/styles/popover.less";
import styles_table from "../RidingReturns/index.less";

interface infoProps {
  [key: string | number]: number | string | null;
}

type numProps = number | null | undefined;

const TABLE_TITLES = [
  "1D",
  "7D",
  "1M",
  "3M",
  "1Y",
  "2Y",
  "3Y",
  "5Y",
  "7Y",
  "10Y",
  "30Y",
  "50Y",
];

// 分位选项
const quantileOptions = [
  { label: "1Y", value: 1 },
  { label: "2Y", value: 2 },
  { label: "3Y", value: 3 },
  { label: "5Y", value: 5 },
  { label: "10Y", value: 10 },
];

let num = 0;

const CriticalPeriod = (props: any) => {
  // console.log(props);
  type Chart = {
    xaxis: string[]; // x轴为字符串数组
    legend: string[];
    yaxis: DataProps[];
  };
  // const table_info = getMergeFromChildList(table_list);
  const chartRef = React.createRef();
  const [dealDate, setDealDate] = useState(null);
  const [startDate, setStartDate] = useState(null);

  const [start, setStart] = useState(null);
  const [end, setEnd] = useState(null);
  const [start2, setStart2] = useState(null);
  const [end2, setEnd2] = useState(null);
  const [fundChart, setFundChart] = useState<Chart>(null);

  const [arr, setArr] = useState([]); //点击效果的存储的数组

  const [hoverInfo, setHoverInfo] = useState<infoProps>({}); //点击悬浮的存储的数组

  const [quantile, setQuantile] = useState(10);

  const [displayType, setDisplayType] = useState("graph"); //graph图 table表

  const [tableList, setTableList] = useState([]);

  const [loading, setLoading] = useState(false); //大表格loading

  const [hasChanged, setHasChanged] = useState(false); //提取数据是否可点击

  const [tableBottomList, setTableBottomList] = useState([]);

  const [bottomLoading, setBottomLoading] = useState(true); //loading

  const [isFirst, setIsFirst] = useState(false); //是否首次点击提取数据

  const [isTdFirst, setIsTdFirst] = useState(false); //是否首次点击指标

  const [columns, setColumns] = useState(false);

  const [arrLoading, setArrLoading] = useState(true); //loading

  const [type, setType] = useState("1");

  // const [nowTime,setNowTime] = useState(null);

  useEffect(() => {
    if (!startDate) return;
    setLoading(true);
    // setArrLoading(true);
    // setBottomLoading(true);
    // reset();
    num++;

    get_critical_deadline_table({
      endDate: dayjs(startDate).format("YYYY-MM-DD"),
      ynum: quantile,
    }).then((res) => {
      // console.log(res)
      if (res?.code == "0" && res?.data?.length > 0) {
        const obj = getMergeFromChildList(res.data);
        // console.log('obj',obj)
        setTableList(obj?.list || []);
        if (num === 1) {
          console.log("num", num);
          setArr(obj?.arr || []);
          setArrLoading(false);
          handleChangeData(obj?.arr);
        }
      } else {
        console.log("num", num);

        setTableList([]);
        if (num === 1) {
          setArr([]);
          setArrLoading(false);
        }
      }
      // setArrLoading(false);
      setLoading(false);
    });

    // get_history_percent().then((res) => {
    //   console.log(111, res);
    // });
  }, [startDate, quantile]);

  const handleGetFirst = () => {
    get_first({type:1}).then((res) => {
      if (res?.code == "0") {
        setIsFirst(!res?.data?.dataList); //首次提取数据
        setIsTdFirst(!res?.data?.tableList); //首次点击指标
      } else {
        setIsFirst(false); //首次提取数据
        setIsTdFirst(false); //首次点击指标
      }
    });
  };

  useEffect(() => {
    handleGetFirst();
    get_last_trading_date().then((res) => {
      if (res?.code == "0") {
        setStartDate(dayjs(res?.data || dayjs(Date.now())));
        setStart(dayjs(res?.data || dayjs(Date.now())).subtract(3, "years"));
        setStart2(dayjs(res?.data || dayjs(Date.now())).subtract(3, "years"));

        setEnd(dayjs(res?.data || dayjs(Date.now())));
        setEnd2(dayjs(res?.data || dayjs(Date.now())));

        setDealDate(dayjs(res?.data || dayjs(Date.now())));
      } else {
        setStartDate(dayjs(dayjs(Date.now())));
        setStart(dayjs(dayjs(Date.now())).subtract(3, "years"));
        setEnd(dayjs(dayjs(Date.now())));
        setStart2(dayjs(dayjs(Date.now())).subtract(3, "years"));
        setEnd2(dayjs(dayjs(Date.now())));
      }
    });
    return () => {
      // reset(true);
    };
  }, []);

  const reset = (bool?: boolean) => {
    console.log("重置");
    if (bool) {
      setQuantile(10);
    }
    setArr([]);
    setFundChart(null);
    setTableBottomList([]);
    setTableList([]);
    setDisplayType("graph"); //graph图 table表
  };

  // useEffect(() => {
  //   if(!displayType)return;
  //   setBottomLoading(true);
  //   setTimeout(()=>{
  //     setBottomLoading(false);

  //   },500)
  // }, [displayType]);

  const clearBlackStyle = () => {
    const ths = document.getElementsByClassName("ant-table-cell hovered");
    for (let index = 0; index < ths.length; index++) {
      const element = ths[index];
      element.classList.remove("hovered");
    }
    const hover_names = document.getElementsByClassName("hover_name hovered");
    for (let index = 0; index < hover_names.length; index++) {
      const element = hover_names[index];
      // console.log('element',element, element.classList.contains("hovered"))
      element.classList.remove("hovered");
    }
  };

  // 保存查询条件
  const handleSaveParams = (e: any) => {
    setStartDate(e);
  };
  // 保存查询条件
  const handleMutileSaveParams = (e: any, type: string) => {
    if (!hasChanged) {
      setHasChanged(true);
    }
    if (type === "start") {
      setStart(e);
    } else {
      setEnd(e);
    }
  };
  // 选择轴线
  const changeAxisType = (t, i) => {
    // setArrLoading(true);
    num++;

    if (!hasChanged) {
      setHasChanged(true);
    }
    const newList = [...arr];
    newList[i] = { ...newList[i], type: t - 1 };
    // console.log(t,newList)
    setArr(newList);
    // setArrLoading(false);
  };
  const handleClickItem = (index: number) => {
    // if (arr?.length === 1) {
    //   message.error("只剩最后一条");
    //   return;
    // }
    if (!hasChanged) {
      setHasChanged(true);
    }
    const deleteList = arr.filter((obj, i) => {
      return i != index;
    });
    setArr(deleteList);
  };

  const onMouseEnter = (row_index: numProps, col_index: numProps) => {
    if (row_index || (row_index === 0 && (col_index || col_index))) {
      clearBlackStyle();
      const ths = document.querySelectorAll("th");
      const item_th = ths[col_index];
      item_th && (item_th.className += " hovered");
      const hover_names = document.getElementsByClassName("hover_name");
      const item_name = hover_names[row_index + 1];
      item_name && (item_name.className += " hovered");
    }
  };
  const onMouseLeave = (row_index: numProps, col_index: numProps) => {
    clearBlackStyle();
  };

  const TableTd = ({ rate, percent, className, row_index, col_index }) => {
    if (rate || rate === 0) {
      // console.log("className", className,"isTdFirst",isTdFirst);
      return (
        <div
          className={cn(
            styles.percent_container,
            className,
            isTdFirst ? null : styles.not_first_container
          )}
          onMouseEnter={_.debounce(
            () => onMouseEnter(row_index, col_index),
            100
          )}
          onMouseLeave={_.debounce(
            () => onMouseLeave(row_index, col_index),
            100
          )}
        >
          <div className={styles.border_container}></div>
          <p
            className={styles.percent_bar}
            style={percent ? { width: `calc(${percent}% - 1px)` } : null}
          ></p>
          <p className={styles.percent_text}>{rate}</p>
          <p className={styles.info_card}>
            <span>点选指标查看历史走势</span>
          </p>
          <p className={styles.percent_hover_container}>
            {percent || percent === 0 ? percent + "%" : "-"}
          </p>
        </div>
      );
    } else if (rate === null) {
      return "-";
    }
    return null;
  };
  const _addRowClass = (record: any, index: number) => {
    // console.log(record,)
    if (record?.rowSpan) {
      return "merge_row";
    }
  };
  const defualtColumns = [
    {
      title: "",
      dataIndex: "parent",
      key: "parent",
      width: 24,
      onCell: (record: any) => {
        return {
          rowSpan: record.rowSpan,
        };
      },
      render: (text: string) => (
        <div
          style={{ width: 24, display: "inline-block" }}
          className={styles.merge_first_td}
        >
          {text}
        </div>
      ),
      align: "center",
    },
    {
      title: "",
      dataIndex: "name",
      key: "name",
      width: 108,
      className: "hover_name",
      render: (text: string) => <div style={{ paddingLeft: 12 }}>{text}</div>,
    },
    {
      title: () => <div>{TABLE_TITLES[0]}</div>,
      dataIndex: TABLE_TITLES[0],
      key: TABLE_TITLES[0],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[0], index),
          row_index: index,
          col_index: 2,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[1]}</div>,
      dataIndex: TABLE_TITLES[1],
      key: TABLE_TITLES[1],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[1], index),
          row_index: index,
          col_index: 3,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[2]}</div>,
      dataIndex: TABLE_TITLES[2],
      key: TABLE_TITLES[2],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[2], index),
          row_index: index,
          col_index: 4,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[3]}</div>,
      dataIndex: TABLE_TITLES[3],
      key: TABLE_TITLES[3],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[3], index),
          row_index: index,
          col_index: 5,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[4]}</div>,
      dataIndex: TABLE_TITLES[4],
      key: TABLE_TITLES[4],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[4], index),
          row_index: index,
          col_index: 6,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[5]}</div>,
      dataIndex: TABLE_TITLES[5],
      key: TABLE_TITLES[5],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[5], index),
          row_index: index,
          col_index: 7,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[6]}</div>,
      dataIndex: TABLE_TITLES[6],
      key: TABLE_TITLES[6],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[6], index),
          row_index: index,
          col_index: 8,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[7]}</div>,
      dataIndex: TABLE_TITLES[7],
      key: TABLE_TITLES[7],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[7], index),
          row_index: index,
          col_index: 9,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[8]}</div>,
      dataIndex: TABLE_TITLES[8],
      key: TABLE_TITLES[8],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[8], index),
          row_index: index,
          col_index: 10,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[9]}</div>,
      dataIndex: TABLE_TITLES[9],
      key: TABLE_TITLES[9],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[9], index),
          row_index: index,
          col_index: 11,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[10]}</div>,
      dataIndex: TABLE_TITLES[10],
      key: TABLE_TITLES[10],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[10], index),
          row_index: index,
          col_index: 12,
        }),
      align: "center",
    },
    {
      title: () => <div>{TABLE_TITLES[11]}</div>,
      dataIndex: TABLE_TITLES[11],
      key: TABLE_TITLES[11],
      // width: 68,
      render: (text: infoProps, records: any, index: number) =>
        TableTd({
          percent: text?.percent,
          rate: text?.value1,
          className: getTableTdClassName(TABLE_TITLES[11], index),
          row_index: index,
          col_index: 13,
        }),
      align: "center",
    },
  ];
  const handleFirstClick = (params: any) => {
    teaching_log(params).then((res) => {
      if (res?.code == "0") {
        handleGetFirst();
      }
    });
  };

  const _onRow = (record, index) => {
    return {
      onClick: (event) => {
        // console.log('event',event,'record',record,'record-name',record.industry,event.target.cellIndex,event.target.parentNode.cellIndex)

        const target = event.target as HTMLTableCellElement;
        if (event.target?.tagName === "TD" && !event.target?.innerHTML) {
          return;
        }
        //首次点击选择指标
        if (isTdFirst) {
          handleFirstClick({ tableList: true ,type:1});
        }
        const columns_types = defualtColumns.map((item) => item.key);
        // console.log('columns_types',columns_types,record,event,event.target.tagName)
        let copyList = [...arr];
        const target_parentNode = target?.offsetParent as HTMLTableCellElement;
        const target_grand_parentNode = target?.parentNode
          ?.parentNode as HTMLTableCellElement;
        const target_grand_grand_parentNode = target?.parentNode?.parentNode
          ?.parentNode as HTMLTableCellElement;

        const first_cell_index =
          target?.cellIndex ||
          target_parentNode?.cellIndex ||
          target_grand_parentNode?.cellIndex ||
          target_grand_grand_parentNode?.cellIndex;
        // console.log(record?.rowSpan,first_cell_index)
        if (
          (record?.rowSpan && first_cell_index === 1) ||
          (record?.rowSpan === 0 && first_cell_index === undefined) ||
          (record?.rowSpan && first_cell_index === undefined)
        ) {
          return;
        }
        setArrLoading(true);

        const cellIndex = record?.rowSpan
          ? first_cell_index
          : first_cell_index + 1;

        let newList = [];
        for (let i = 0; i < copyList.length; i++) {
          const element = copyList[i];
          if (
            (cellIndex || cellIndex === 0) &&
            element.col_name == columns_types[cellIndex] &&
            element.row_index === index
          ) {
            continue;
          }
          newList.push(element);
        }
        // console.log('record',record)
        if (newList.length !== copyList.length) {
          copyList = [...newList];
        } else {
          copyList.push({
            col_name: columns_types[cellIndex],
            col_index: cellIndex,
            row_index: index,
            row_name: record?.name,
            id: record[columns_types[cellIndex]]?.id,
          });
        }
        if (copyList?.length > 10) {
          message.error("最多可添加十个指标");
          setArrLoading(false);
          return;
        }
        if (!hasChanged) {
          setHasChanged(true);
        }

        // console.log(target.cellIndex,target.offsetParent.cellIndex,cellIndex,columns_types[cellIndex])
        // console.log(copyList)
        num++;
        // console.log("num",num)
        setArr(copyList);
        setArrLoading(false);
      }, // 点击行
    };
  };

  const getTableTdClassName = (key, index) => {
    const ele = arr.filter((item) => {
      // console.log('item.name',item.name,'key',key,'index',index,'item.index',item.index)
      return item.col_name === key && index === item.row_index;
    })[0];
    let classname;
    // console.log('ele',ele)
    if (ele) {
      // style = {border:"2px solid #363C4E"};
      // return style;
      classname = "checked";
      return classname;
    }
    // name =  "blue";
    // console.log('-------name',color,ele,arr)
    return null;
  };

  const downloadImg = (title: string) => {
    // console.log(title, chartRef.current);

    if (chartRef?.current) {
      chartRef?.current?.downloadImg(title);
    }
  };

  const tableClass = (arr: any, max?: number) =>
    cn({
      [styles_table.scrollTable]: true,
      hidden: arr?.length < 8,
      [styles_table.scrollTableFix]: max && arr?.length > max,
      [styles_table.empty]: _.isEmpty(arr),
      [styles_table.ridingTable]: true,
      [styles.bottom_table]: true,
    });

  const handleChangeTypeData = (type:string,data:any,param:any)=>{
    const yaxis = data?.axis?.yaxis?.length > 0 ? data?.axis?.yaxis : [];
    let new_columns: any = [
      {
        title: "日期",
        dataIndex: "endDate",
        key: "endDate",
        align: "center",
        width: 100,
      },
    ];
    const new_yaxis = yaxis.map((item, index) => {
      const new_item = arr.filter(
        (obj) => item?.label === obj?.row_name + " " + obj?.col_name
      );
      console.log("item", item);
      new_columns.push({
        title: () => (
          <div title={item?.label || "-"} className={styles.ellipsis5}>
            {item?.label || "-"}
          </div>
        ),
        dataIndex: param ? param[index]?.id : arr[index]?.id,
        key: param ? param[index]?.id : arr[index]?.id,
        align: "right",
        // width:150,
        render: (text: any) => {
          if (!text) return "-";
          // console.log('param[index]?.id',param[index]?.id,text,text[(param[index]?.id)],Object.keys(text),Object.keys(text).includes((param[index]?.id)))
          const show_value =
            text?.value1 || text?.value1 === 0
              ? text?.value1
              : param
              ? text[param[index]?.id]?.value1
              : text[arr[index]?.id]?.value1
              ?text[arr[index]?.id]?.value1:text;
          return show_value || show_value === 0 ? show_value : "-";
        },
      });
      return {
        ...item,
        yAxisIndex: new_item?.length > 0 ? new_item[0]?.type : undefined, //调整左右轴
      };
    });
    setColumns(new_columns);

    if (new_yaxis?.length > 0) {
      setFundChart({
        ...(data?.axis || {}),
        yaxis: new_yaxis,
      });
    } else {
      setFundChart(null);
    }

    setColumns(new_columns);

    setTableBottomList(data?.dataList);
  }

  const handleChangeData = (param?: Array<any>) => {
    // if(!hasChanged)return;
    // 取消请求 (message 参数是可选的)
    // source.cancel('Operation canceled by the user.');
    setBottomLoading(true);
    if(type=="1"){
      //原值
      get_critical_deadline_chart({
        startDate: dayjs(start).format("YYYY-MM-DD"),
        endDate: dayjs(end).format("YYYY-MM-DD"),
        ids:
          param?.length > 0
            ? param.map((item) => item.id)
            : arr.map((item) => item.id),
        // cancelToken: source.token,
        // signal: controller.signal
      }).then((res) => {
        console.log(res);
        if (res?.code == "0") {
          const data = res?.data;
          handleChangeTypeData("1",data,param);
          
        } else {
          setFundChart(null);
          setTableBottomList([]);
        }
        setBottomLoading(false);
      });

    }else{
      //分位值
      get_critical_deadline_percent({
        startDate: dayjs(start).format("YYYY-MM-DD"),
        endDate: dayjs(end).format("YYYY-MM-DD"),
        ids:
          param?.length > 0
            ? param.map((item) => item.id)
            : arr.map((item) => item.id),
        year:quantile
        // cancelToken: source.token,
        // signal: controller.signal
      }).then((res) => {
        console.log(res);
        if (res?.code == "0") {
          const data = res?.data;
          handleChangeTypeData("1",data,param);
          
        } else {
          setFundChart(null);
          setTableBottomList([]);
        }
        setBottomLoading(false);
      });

    }
   
  };

  const handleClick = () => {
    if (!hasChanged) return;

    setStart2(start);
    setEnd2(end);

    //首次点击提取数据
    if (isFirst) {
      handleFirstClick({ dataList: true,type:1 });
    }
    // setNowTime(new Date().getTime());
    handleChangeData();
  };

   // 更改筛选条件
   const handleChangeType = (e: any) => {
    setType(e.key);
    setHasChanged(true);
    
  };

  const menu = (
    <Menu onClick={handleChangeType} selectedKeys={type}>
      <Menu.Item key="1">原值</Menu.Item>
      <Menu.Item key="2">分位数</Menu.Item>
    </Menu>
  );

  

  return (
    (<PageWrapper narrow scrollY minWidth="1068px">
      <div id="critical_period_scroll_container">
        <Title style={{margin:"2px 0 0 16px"}}>关键期限</Title>
        <FormContainer>
          <CusDatePicker
            label="日期"
            startValue={startDate}
            single={true}
            idName1="critical-date"
            onChange={handleSaveParams}
            className={styles.customDatePicker}
            disabledDate={(currentDate) => {
              return dayjs(currentDate) > dayjs(Date.now());
            }}
          />
          <CustomizeRadio
            className="ml24"
            label="分位时间范围"
            options={quantileOptions}
            value={quantile}
            setValue={setQuantile}
          />
        </FormContainer>

        <div className={styles.merge_table_container}>
          <Table
            tableLayout="fixed"
            columns={defualtColumns as ColumnsType}
            rowClassName={(record, index) => _addRowClass(record, index)}
            rowKey={(r: infoProps) => r?.name}
            dataSource={tableList || []}
            onRow={(record, index) => {
              return _onRow(record, index);
            }}
            // bordered
            pagination={false}
            loading={loading}
          />
        </div>
        <BottomContainer>
          <Spin spinning={arrLoading}>
            <LeftContainer>
              <RedContainer disabled={!hasChanged}>
                <div>
                  <span></span>
                  <div>
                    <div className={styles.dropdown_container}>
                      
                      <div className={styles.firstBlock_left_header_left_hover}>
                        <Dropdown
                          overlayClassName={styles.dropMenu}
                          overlay={menu}
                          trigger={["click"]}
                        >
                          <div className={styles.text_container}>
                            <p className={styles.title}>历史走势 </p>
                            <p> - </p>
                            <span>
                              {type === "1"? "原值" : "分位数"}
                            </span>
                            <img src={select_arrow} alt="下拉" />
                          </div>
                        </Dropdown>
                      </div>
                    </div>
                  </div>
                  {/* <p>历史走势 - </p> */}
                </div>
                {isFirst ? (
                  <Popover
                    overlayClassName={cn("popoverDarkStyle")}
                    placement="right"
                    trigger="hover"
                    content={() => (
                      <div>
                        指标有变动，请点击{" "}
                        <span className={styles.bolder_text}>提取数据</span>{" "}
                        刷新图表
                      </div>
                    )}
                  >
                    <div>
                      <RedBtn disabled={!hasChanged} onClick={handleClick}>
                        提取数据
                      </RedBtn>
                    </div>
                  </Popover>
                ) : (
                  <RedBtn disabled={!hasChanged} onClick={handleClick}>
                    提取数据
                  </RedBtn>
                )}
              </RedContainer>
              <DateContainer>
                <CusDatePicker
                  label=""
                  startValue={start}
                  endValue={end}
                  idName1="critical-date-left"
                  idName2="critical-date-right"
                  onChange={handleMutileSaveParams}
                  className={styles.customDatePicker}
                  disabledDate={(currentDate) => {
                    return (
                      dayjs(currentDate) > dayjs(Date.now()) ||
                      dayjs(currentDate) > dayjs(end)
                    );
                  }}
                  disabledEndDate={(currentDate) => {
                    return dayjs(currentDate) > dayjs(Date.now());
                  }}
                />
              </DateContainer>
              <ListContainer>
                {arr?.length > 0
                  ? arr.map((item, index) => (
                      <List key={item?.row_name + item?.col_name}>
                        <Select
                          dropdownMatchSelectWidth={false}
                          popupClassName="select_option"
                          value={
                            item?.type && item?.type === 1 ? "右轴" : "左轴"
                          }
                          suffixIcon={
                            <span className="findfit_icon findfit_icon_arrow "></span>
                          }
                          onChange={(v) => changeAxisType(v, index)}
                        >
                          {/* eslint-disable-next-line @typescript-eslint/no-shadow */}
                          {AxisArr.map((k, i) => (
                            <Select.Option key={i + 1} value={i + 1}>
                              {k}
                            </Select.Option>
                          ))}
                        </Select>
                        <Divider />
                        <ColorContainer color={getBaseColors()[index]} />
                        <TextContainer>
                          {item?.row_name} {item?.col_name}
                        </TextContainer>
                        <ButtonContainer>
                          <Divider />
                          <DeleteBtnContainer
                            onClick={() => {
                              handleClickItem(index);
                            }}
                          >
                            <DeleteBtn></DeleteBtn>
                          </DeleteBtnContainer>
                        </ButtonContainer>
                      </List>
                    ))
                  : null}
              </ListContainer>
            </LeftContainer>
          </Spin>
          <RightContainer>
            <div className={styles.chart_head_container}>
              <div className={styles.chart_head}>
                <span>{`历史走势 - ${type=="1"?"原值":"分位数"}（${
                  start2 ? dayjs(start2).format("YYYY/MM/DD") : "-"
                }-${end2 ? dayjs(end2).format("YYYY/MM/DD") : "-"}）`}</span>
              </div>
              <div className={styles.btn_container}>
                {/* {console.log('fundChart',fundChart)} */}
                {displayType === "graph" && (
                  <>
                    <span
                      title="导出图片"
                      className={cn(styles.download,!(fundChart?.xaxis?.length>0)?styles.download_disabled:null)}
                      // style={{ marginRight: 2 }}
                      onClick={
                        _.isEmpty(fundChart?.yaxis)
                          ? () => {}
                          : () =>
                              downloadImg(
                                `历史走势 - ${type=="1"?"原值":"分位数"}（${dayjs(start2).format(
                                  "YYYY/MM/DD"
                                )}-${dayjs(end2).format("YYYY/MM/DD")}）`
                              )
                      }
                    ></span>
                    <div className={styles.divider}></div>
                  </>
                )}
                <GraphOrTable value={displayType} setValue={setDisplayType} />
              </div>
            </div>
            <Spin spinning={bottomLoading}>
              <div style={{ paddingTop: 8 }}>
                <div
                  style={{
                    width: "100%",
                    height: 340,
                    display: displayType === "graph" ? "block" : "none",
                  }}
                >
                  {fundChart?.xaxis?.length > 0 ? (
                    <Area
                      idName="fund-area"
                      xAxis={fundChart?.xaxis}
                      data={fundChart?.yaxis || []}
                      legend={fundChart?.legend || []}
                      color={getBaseColors()}
                      ref={chartRef}
                      notShowArea
                      showLine
                      smooth
                      print
                      notShowStack
                      stickToBottom
                      // numFixed={"0.0000"}
                    />
                  ) : (
                    <EventEmpty
                      title="暂无数据"
                      imgStyle={{ marginTop: 35 }}
                    ></EventEmpty>
                  )}
                </div>
                <div
                  style={{
                    width: "100%",
                    display: displayType === "table" ? "block" : "none",
                  }}
                >
                  <Table
                    tableLayout="fixed"
                    className={tableClass([], 7)}
                    columns={columns || []}
                    dataSource={tableBottomList || []}
                    scroll={{ y: 334, x: true }}
                    pagination={false}
                    // sticky
                    rowKey={(r: infoProps) => r?.endDate}
                  ></Table>
                </div>
              </div>
            </Spin>
          </RightContainer>
        </BottomContainer>
      </div>
    </PageWrapper>)
  );
};

export default CriticalPeriod;
